/**
 * @author Alfred Wang
 * @note 操作JDBC的底层操作，需要上层类的包装，本类为抽象类，将不可实例化，使用静态方法即可
 */

package team.wh1tegive.db;

import java.sql.*;

import team.wh1tegive.misc.Log;

public abstract class DatabaseAction {
    private static Connection connection;

    static {
        try {
            Class.forName("org.sqlite.JDBC");
            Log.writeLog("Successfully Loaded the DataBase Driver.");
        } catch (ClassNotFoundException e) {
            Log.writeError("Can NOT Find the Driver to the DataBase: " + e.getMessage());
        }
    }

    public static ResultSet executeQuery(String sql) {
        Statement statement;
        ResultSet resultSet = null;

        try {
            if (connection != null)
                closeConnection();
            connection = DriverManager.getConnection("jdbc:sqlite:MoneyManager.db");
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
        } catch (SQLException e) {
            Log.writeError("Execute Query Failed: " + e.getMessage());
        }
        return resultSet;
    }

    public static int executeUpdate(String sql) {
        Statement statement;
        int count = 0;
        try {
            if (connection != null)
                closeConnection();
            connection = DriverManager.getConnection("jdbc:sqlite:MoneyManager.db");
            statement = connection.createStatement();
            count = statement.executeUpdate(sql);
            statement.close();
            closeConnection();
        } catch (SQLException e) {
            Log.writeError("Execute UpdateQuery Failed: " + e.getMessage());
        }
        return count;
    }

    public static void closeConnection() {
        try {
            connection.close();
        } catch (SQLException e) {
            Log.writeError("Close Connection Failed: " + e.getMessage());
        }
    }
}
